/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.constant.enums;

import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.json.utils.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * 数据库建模模型字段类型枚举
 * @author lj
 * @date 2025-05-15
 */
@AllArgsConstructor
@Getter
public enum IsfdDatabaseModelFieldTypeEnum {
    FLOAT("浮点值"),
    STRING("字符串"),
    INTEGER("整型"),
    TIMESTAMP("时间戳"),
    DOUBLE_ARRAY("数列"),
    DICT("字典"),
    BOOL("布尔值"),
    MODEL("模型"),
    OBJECT("对象"),
    IMAGE("图片"),
    FILE("文件"),
    LIST("列表"),
    ARRAY("数组"),
    RANGE("范围值");

    private final String value;

    public static IsfdDatabaseModelFieldTypeEnum forValue(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        for (IsfdDatabaseModelFieldTypeEnum isfdDatabaseModelFieldTypeEnum : IsfdDatabaseModelFieldTypeEnum.values()) {
            if (isfdDatabaseModelFieldTypeEnum.getValue().equals(value)) {
                return isfdDatabaseModelFieldTypeEnum;
            }
        }
        return null;
    }

    public static Object convertToType(Object value, String valueType) throws Exception {

        IsfdDatabaseModelFieldTypeEnum fieldType = forValue(valueType);
        if (fieldType == null) {
            throw new Exception("不支持的数据类型: " + valueType);
        }

        if (value == null) {
            return null;
        }

        // 如果是字符串类型，且 value 不是 String，就直接报错
        if ((fieldType == STRING
            || fieldType == IMAGE
            || fieldType == FILE)
            && !(value instanceof String)) {
            throw new Exception("字段类型是 " + fieldType + "，但传入值不是字符串: " + value.getClass().getSimpleName());
        }

        String valueString = value.toString();

        return switch (fieldType) {
            case STRING, IMAGE, FILE -> valueString;
            case INTEGER -> Integer.parseInt(valueString);
            case TIMESTAMP -> Long.parseLong(valueString);
            case FLOAT -> Double.parseDouble(valueString);
            case DOUBLE_ARRAY -> {
                if (value instanceof String) {
                    String[] parts = valueString.split(",");
                    List<Double> doubles = new ArrayList<>();
                    for (String part : parts) {
                        doubles.add(Double.parseDouble(part.trim()));
                    }
                    yield doubles;
                } else if (value instanceof List<?> list) {
                    List<Double> doubles = new ArrayList<>();
                    for (Object item : list) {
                        doubles.add(Double.parseDouble(item.toString()));
                    }
                    yield doubles;
                } else {
                    throw new Exception("无法将值转换为 List<Double> 类型");
                }
            }
            case DICT -> {
                if (value instanceof String) {
                    yield parseJsonToMap(valueString);
                } else if (value instanceof Map<?, ?>) {
                    yield value;
                } else {
                    throw new Exception("无法将值转换为 dict 类型");
                }
            }
            case ARRAY -> {
                if (value instanceof List<?> list) {
                    yield value;
                } else if (value instanceof String) {
                    try {
                        yield parseJsonToList(valueString);  // 推荐 parseJsonToList 返回 List<Map<String, Object>> 或 List<Object>
                    } catch (Exception e) {
                        throw new Exception("无法将值转换为 List 类型");
                    }
                }  else {
                    throw new Exception("无法将值转换为 List 类型");
                }
            }
            case BOOL -> Boolean.parseBoolean(valueString);
            case MODEL, LIST -> {
                if (value instanceof List<?> list) {
                    for (Object item : list) {
                        if (!(item instanceof Map<?, ?>)) {
                            throw new Exception("模型/列表数据必须是 List<Map<String, Object>>，但包含了 " + item.getClass().getSimpleName());
                        }
                    }
                    yield value; // 已经是符合格式的 List<Map>
                } else if (value instanceof String) {
                    yield parseJsonToListOfMaps(valueString); // 尝试解析 JSON
                } else {
                    throw new Exception("无法将值转换为 List<Map<String, Object>> 类型");
                }
            }
            case OBJECT -> {
                if (value instanceof Map) {
                    yield value;
                } else {
                    yield parseJsonToMap(valueString);
                }
            }
            case RANGE -> {
                if (value instanceof String) {
                    String trimmed = valueString.replaceAll("\\s+", ""); // 去掉所有空格
                    // 使用正则匹配两个 double（可能是负数），用 "-" 分隔
                    // 支持格式如 -12.5--10.0、-5.0-5.0、0.0-10.0 等
                    Pattern pattern = Pattern.compile("^(-?\\d+(\\.\\d+)?)-(-?\\d+(\\.\\d+)?)$");
                    Matcher matcher = pattern.matcher(trimmed);
                    if (matcher.matches()) {
                        try {
                            Double.parseDouble(matcher.group(1));
                            Double.parseDouble(matcher.group(3));
                            yield valueString.trim(); // 校验通过，返回原始字符串（保留空格形式也可）
                        } catch (NumberFormatException e) {
                            throw new Exception("范围值不是有效的数字: " + valueString);
                        }
                    } else {
                        throw new Exception("范围格式错误，应为 'number - number'（支持负数）形式: " + valueString);
                    }
                } else {
                    throw new Exception("范围值必须是字符串类型: " + value);
                }
            }
        };
    }

    // 将 JSON 字符串转换为 Map 的方法
    private static Map<String, Object> parseJsonToMap(String json) throws Exception {
        // 假设使用 Jackson 或 Gson 库进行 JSON 解析
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(json, new TypeReference<>() {});
    }

    private static List<Map<String, Object>> parseJsonToListOfMaps(String json) throws Exception {
        try {
            return JsonUtils.parseObject(json, new TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception e) {
            throw new Exception("无法解析 JSON 为 List<Map<String, Object>>: " + json, e);
        }
    }

    private static List<Object> parseJsonToList(String json) throws Exception {
        try {
            return JsonUtils.parseObject(json, new TypeReference<List<Object>>() {});
        } catch (Exception e) {
            throw new Exception("无法解析 JSON 为 List<>: " + json, e);
        }
    }
}
